# This tutorial will introduce simple implementations of while loops
# in Python.
# Here's a while loop that calculates the factorial of n. Start with n = 4
# to make sure things are working properly. The loop executes until n > 1.
# That is, the the last iteration of the loop will occur when n = 2. (You
# could actually let the while loop run until n = 1 since factorial*1 =
# factorial).
n = 4
print('n =', n)
factorial = 1
while n > 1:
factorial = factorial*n
n = n - 1
print('n! =', factorial)
n = 4 n! = 24
# Here's a more interesting factorial
n = 50
print('n =', n)
factorial = 1
while n > 1:
factorial = factorial*n
n = n - 1
print('n! =', factorial)
n = 50 n! = 30414093201713378043612608166064768844377641568960512000000000000
# We can force the number to be written in scientific notation while keeping
# only some of the digits after the decimal point using:
print('n! =', float(factorial))
n! = 3.0414093201713376e+64
# Here's a a crazy big number...
n = 170
print('n =', n)
factorial = 1
while n > 1:
factorial = factorial*n
n = n - 1
print('n! =', float(factorial))
n = 170 n! = 7.257415615307999e+306
# Here's the factorial of a user-entered value.
n = int(input("Enter an integer: "))
print('n =', n)
factorial = 1
while n > 1:
factorial = factorial*n
n = n - 1
print('n! =', float(factorial))
Enter an integer: 17 n = 17 n! = 355687428096000.0
# Maybe you want to the user to be able to enter only integer numbers with
# appropriate error messages.
# See the nested control structure tutorial for an implementation of this
# check. That tutorial will also show you how to calculate the factorials
# of a bunch of n values and then plot the results vs n.